const express = require("express");
const router = express.Router();
const { Setting } = require("../../models");
const { success,failure, NotFoundError } = require("../../utils/response");

// 查询系统设置详情
router.get("/", async function (req, res, next) {
  try {
    const setting = await getSetting();
    console.log(setting,'setting111')
    success(res, "查询系统设置详情成功", setting);
  } catch (error) {
    failure(res,  error);
  }
});



// 更新系统设置（PUT）
router.put("/", async function (req, res, next) {
  try {
    const setting =  await  getSetting();
    const body = filterBody(req);
    await setting.update(body);
    success(res, "更新系统设置成功", setting);
  
  } catch (error) {
    failure(res,  error);
  }
});



async function getSetting  () {
    const setting = await Setting.findOne()
    // console.log(setting,'setting')
    if (!setting) {
        throw new NotFoundError(`初始化系统设置未找到。`);
    }
    return setting;
}
/**
 * 白名单过滤（强参数过滤）去掉没有用到的参数
 * @param {*} req
 * @returns
 */
function filterBody(req) {
  return {
    name: req.body.name,
    icp: req.body.icp,
    copyright: req.body.copyright,
  };
}

module.exports = router;
